<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="会员姓名" prop="name">
            <el-input v-model="form.name" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remarks" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="id" />
        <el-table-column prop="name" label="会员姓名" />
        <el-table-column prop="phone" label="手机号" width="100"/>
        <el-table-column prop="cardId" label="会员卡" width="100" align="center">
          <template slot-scope="scope">
            <el-popover
              v-for="card in scope.row.memberCards"
              :key="card.id"
              placement="top"
              width="200"
              trigger="click"
              style="margin-right: 5px;"
            >
              <div>
                <p>卡号: {{ card.cardNo }}</p>
                <p>卡类型: {{ card.cardType }}</p>
                <p>结余: {{ card.amount }}元</p>
                <p>发卡时间: {{ formatDate(card.createTime) }}</p>
                <p>有效期: {{ card.validEndTime ? formatDate(card.validEndTime) : '永久有效' }}</p>
              </div>
              <div style="text-align: center; margin-top: 10px;">
                <div style="display: flex; justify-content: space-around; margin-bottom: 8px;">
                  <el-button size="mini" @click="handleRecharge(card)">充值</el-button>
                  <el-button size="mini" @click="handleViewRecords(card)">记录</el-button>
                </div>
                <div style="display: flex; justify-content: space-around;">
                  <el-button size="mini" @click="handleEditCard(card, scope.row)">编辑</el-button>
                  <el-button size="mini" @click="handleRefund(card)">退卡</el-button>
                </div>
              </div>
              <el-button
                slot="reference"
                size="mini"
                type="primary"
                style="margin: 2px;"
              >
                {{ card.cardType }}
              </el-button>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="levelName" label="会员等级" align="center">
          <template slot-scope="scope">
            <el-tag :type="getMemberLevelType(scope.row.levelName)">
              {{ scope.row.memberLevels.levelName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currentPoints" label="当前积分" />
        <el-table-column prop="remarks" label="备注" />
        <el-table-column prop="createdAt" label="创建时间" />
        <el-table-column prop="updatedAt" label="更新时间" />
        <el-table-column v-if="checkPer(['admin','members:edit','members:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
              direction="vertical"
            />
            <div style="display: flex; flex-direction: column; align-items: center;">
              <el-tooltip content="开卡" placement="top">
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleAddCard(scope.row)"
                  style="width: 30px; padding: 5px; margin-bottom: 3px;"
                >
                  <svg-icon icon-class="addCard" />
                </el-button>
              </el-tooltip>
              <el-tooltip content="添加宠物" placement="top">
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleAddPet(scope.row)"
                  style="width: 30px; padding: 5px;"
                >
                  <svg-icon icon-class="addPet" />
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
      <card-form
        :visible.sync="cardFormVisible" 
        :member="selectedMember"
        :member-cards="memberCards"
        :is-edit="isEditMode"
        :editing-card="editingCard"
        @update:visible="handleCardFormVisibleChange"
      />
      
      <!-- 添加充值对话框 -->
      <el-dialog
        title="会员卡充值"
        :visible.sync="rechargeDialogVisible"
        width="400px"
      >
        <el-form
          ref="rechargeForm"
          :model="rechargeForm"
          :rules="rechargeRules"
          label-width="100px"
          size="small"
        >
          <el-form-item label="充值金额" prop="amount">
            <el-input-number
              v-model="rechargeForm.amount"
              :min="0"
              :precision="2"
              :step="10"
            />
          </el-form-item>
          <el-form-item label="赠送金额" prop="giftAmount">
            <el-input-number
              v-model="rechargeForm.giftAmount"
              :min="0"
              :precision="2"
              :step="5"
            />
          </el-form-item>
          <el-form-item label="支付方式" prop="paymentMethod">
            <el-select v-model="rechargeForm.paymentMethod" style="width: 100%">
              <el-option label="现金" value="CASH" />
              <el-option label="微信" value="WECHAT" />
              <el-option label="支付宝" value="ALIPAY" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="rechargeForm.remarks"
              type="textarea"
              :rows="2"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="rechargeDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitRecharge">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 添加充值记录弹窗 -->
      <el-dialog
        title="充值记录"
        :visible.sync="rechargeRecordVisible"
        width="800px"
      >
        <el-table
          :data="rechargeRecords"
          style="width: 100%"
          v-loading="recordsLoading"
        >
          <el-table-column
            prop="amount"
            label="充值金额"
            align="center"
          />
          <el-table-column
            prop="giftAmount"
            label="赠送金额"
            align="center"
          />
          <el-table-column
            prop="paymentFee"
            label="支付费用"
            align="center"
          >
            <template slot-scope="scope">
              {{ Number(scope.row.amount) + Number(scope.row.giftAmount) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="paymentMethod"
            label="支付方式"
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.paymentMethod === 'CASH' ? '现金' : 
                 scope.row.paymentMethod === 'WECHAT' ? '微信' : 
                 scope.row.paymentMethod === 'ALIPAY' ? '支付宝' : 
                 scope.row.paymentMethod }}
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="充值时间"
            align="center"
          >
            <template slot-scope="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="80"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleRevoke(scope.row)"
              >
                撤销
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination
            background
            layout="total, prev, pager, next"
            :total="total"
            :current-page.sync="page"
            @current-change="handlePageChange"
          />
        </div>
      </el-dialog>

      <!-- 添加退卡对话框 -->
      <el-dialog
        title="退卡"
        :visible.sync="refundDialogVisible"
        width="400px"
      >
        <el-form
          ref="refundForm"
          :model="refundForm"
          :rules="refundRules"
          label-width="100px"
          size="small"
        >
          <el-form-item label="会员卡号">
            <span>{{ currentCard ? currentCard.cardNo : '' }}</span>
          </el-form-item>
          <el-form-item label="开卡时间">
            <span>{{ currentCard ? formatDate(currentCard.createTime) : '' }}</span>
          </el-form-item>
          <el-form-item label="总充值金额">
            <span>{{ currentCard ? currentCard.totalRechargeAmount : 0 }}元</span>
          </el-form-item>
          <el-form-item label="总赠送金额">
            <span>{{ currentCard ? currentCard.totalGiftAmount : 0 }}元</span>
          </el-form-item>
          <el-form-item label="卡内余额">
            <span>{{ currentCard ? currentCard.amount : 0 }}元</span>
          </el-form-item>
          <el-form-item label="应退金额" prop="amount">
            <el-input-number
              v-model="refundForm.amount"
              :min="0"
              :max="currentCard ? currentCard.amount : 0"
              :precision="2"
              :step="10"
              style="width: 220px"
            />
          </el-form-item>
          <el-form-item label="支付方式" prop="paymentMethod">
            <el-select v-model="refundForm.paymentMethod" style="width: 220px">
              <el-option label="现金" value="CASH" />
              <el-option label="微信" value="WECHAT" />
              <el-option label="支付宝" value="ALIPAY" />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="refundDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitRefund">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import crudMembers from '@/api/vip/members'
import { getMemberCards, rechargeCard, getRechargeRecords, revokeRecharge, refundCard } from '@/api/vip/card'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import CardForm from '@/views/vip/card/CardForm.vue'
import dayjs from 'dayjs'

const defaultForm = { name: null, phone: null, remarks: null }
export default {
  name: 'Members',
  components: { pagination, crudOperation, rrOperation, udOperation, CardForm },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '会员管理', url: 'api/members', idField: 'id', sort: 'id,desc', crudMethod: { ...crudMembers }})
  },
  data() {  
    return {
      permission: {
        add: ['admin', 'members:add'],
        edit: ['admin', 'members:edit'],
        del: ['admin', 'members:del']
      },
      rules: {
        name: [
          { required: true, message: '会员姓名不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' }
        ]
      },
      cardFormVisible: false,
      selectedMember: null,
      loading: false,
      memberCards: [],
      isEditMode: false,
      editingCard: null,
      rechargeDialogVisible: false,
      rechargeForm: {
        amount: null,
        giftAmount: null,
        paymentMethod: 'CASH',
        memberLevel: 'NORMAL',
        cardId: null,
        remarks: null
      },
      rechargeRules: {
        amount: [
          { required: true, message: '请输入充值金额', trigger: 'blur' },
          { type: 'number', message: '金额必须为数字' }
        ],
        paymentMethod: [
          { required: true, message: '请选择支付方式', trigger: 'change' }
        ],
        memberLevel: [
          { required: true, message: '请选择会员等级', trigger: 'change' }
        ]
      },
      rechargeRecordVisible: false,
      rechargeRecords: [],
      recordsLoading: false,
      page: 1,
      total: 0,
      currentCard: null,
      refundDialogVisible: false,
      refundForm: {
        cardId: null,
        amount: null,
        paymentMethod: 'CASH'
      },
      refundRules: {
        amount: [
          { required: true, message: '请输入退款金额', trigger: 'blur' },
          { type: 'number', message: '金额必须为数字' }
        ],
        paymentMethod: [
          { required: true, message: '请选择支付方式', trigger: 'change' }
        ]
      },
      // 会员等级标签类型映射
      levelTypeMap: {
        '普通会员': '',
        '银卡会员': 'info',
        '金卡会员': 'warning',
        '钻石会员': 'success'
      }
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    async handleAddCard(row) {
      this.selectedMember = { ...row }
      try {
        const response = await getMemberCards(row.id)
        console.log('Member cards:', response)
        this.memberCards = response || []
      } catch (error) {
        console.error('获取会员卡信息失败:', error)
        this.memberCards = []
      }
      this.cardFormVisible = true
    },
    handleCardFormVisibleChange(visible) {
      this.cardFormVisible = visible
      if (!visible) {
        this.selectedMember = null
        this.memberCards = []
      }
    },
    getDictLabel(value) {
      // console.log(this.dict.card_type,value)
      // const type = this.dict.card_type.find(t => t.value === value)
      // console.log(this.dict.card_type,value)
      // return type ? type.label : value
    },
    handleEditCard(card, member) {
      this.selectedMember = { ...member }
      this.editingCard = { ...card }
      this.isEditMode = true
      this.memberCards = member.memberCards || []
      this.cardFormVisible = true
    },
    formatDate(date) {
      if (!date) return ''
      return dayjs(date).format('YYYY-MM-DD')
    },
    handleRecharge(card) {
      this.rechargeForm = {
        cardId: card.id,
        amount: null,
        giftAmount: null,
        paymentMethod: 'CASH',
        remarks: null
      }
      this.currentCard = card // 保存当前操作的卡信息
      this.rechargeDialogVisible = true
    },
    submitRecharge() {
      this.$refs.rechargeForm.validate(async(valid) => {
        if (valid) {
          try {
            await rechargeCard(this.rechargeForm)
            this.$message.success('充值成功')
            this.rechargeDialogVisible = false
            this.rechargeForm = { // Reset form
              amount: null,
              giftAmount: null,
              paymentMethod: 'CASH',
              memberLevel: 'NORMAL',
              cardId: null
            }
            this.crud.refresh() // Refresh table data
          } catch (error) {
            console.error('充值失败:', error)
            const errorMessage = error.response && error.response.data && error.response.data.message
            this.$message.error(errorMessage || '充值失败')
          }
        }
      })
    },
    async handleViewRecords(card) {
      this.currentCard = card
      this.rechargeRecordVisible = true
      await this.loadRechargeRecords()
    },
    async loadRechargeRecords() {
      if (!this.currentCard) return
      this.recordsLoading = true
      try {
        const response = await getRechargeRecords(this.currentCard.id)
        this.rechargeRecords = response.content || []
        this.total = response.totalElements || 0
      } catch (error) {
        console.error('获取充值记录失败:', error)
        this.$message.error('获取充值记录失败')
      } finally {
        this.recordsLoading = false
      }
    },
    handlePageChange(page) {
      this.page = page
      this.loadRechargeRecords()
    },
    async handleRevoke(record) {
      try {
        await this.$confirm('确认要撤销该笔充值记录吗？', '提示', {
          type: 'warning'
        })
        
        await revokeRecharge(record.id)
        this.$message.success('撤销成功')
        await this.loadRechargeRecords() // 重新加载记录
        this.crud.refresh() // 刷新会员卡信息
      } catch (error) {
        if (error !== 'cancel') { // 用户取消操作不提示错误
          console.error('撤销失败:', error)
          const errorMessage = error.response && error.response.data && error.response.data.message
          this.$message.error(errorMessage || '撤销失败')
        }
      }
    },
    handleRefund(card) {
      this.currentCard = card
      this.refundForm = {
        cardId: card.id,
        amount: card.amount,
        paymentMethod: 'CASH'
      }
      this.refundDialogVisible = true
    },
    submitRefund() {
      this.$refs.refundForm.validate(async (valid) => {
        if (valid) {
          try {
            await refundCard(this.refundForm);
            this.$message.success('退卡成功');
            this.refundDialogVisible = false;
            this.refundForm = {
              cardId: null,
              amount: null,
              paymentMethod: 'CASH'
            };
            this.crud.refresh();
          } catch (error) {
            console.error('退卡失败:', error);
            const errorMessage = error.response && error.response.data && error.response.data.message;
            this.$message.error(errorMessage || '退卡失败');
          }
        }
      });
    },
    // 获取会员等级对应的标签类型
    getMemberLevelType(level) {
      return this.levelTypeMap[level] || ''
    }
  }
}
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 会员等级标签样式 */
.el-tag {
  margin-right: 5px;
}
</style>
